/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.sec;

import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.persistent.Empleado;
import dp1.titandevelop.titano.persistent.Perfil;
import dp1.titandevelop.titano.persistent.Usuario;
import dp1.titandevelop.titano.service.EmpleadoService;
import dp1.titandevelop.titano.service.PerfilService;
import dp1.titandevelop.titano.service.UsuarioService;
import dp1.titandevelop.titano.service.ValidacionService;
import java.awt.Dimension;
import java.util.List;
import javax.swing.JOptionPane;

import org.apache.cayenne.ObjectContext;

import org.apache.cayenne.access.DataContext;

/**
 *
 * @author chrestean
 */
public class ModulosT_SEG_AUsuNuevo extends javax.swing.JInternalFrame {

    public ModulosT_SEG_AUsuNuevo() {
        initComponents();
        ValidacionService validacionService = new ValidacionService();
        validacionService.SLetras(this.txtUsuario);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblEmpleado = new javax.swing.JLabel();
        btnBuscarEmpleado = new javax.swing.JButton();
        txtIDEmpleado = new javax.swing.JTextField();
        txtEmpleado = new javax.swing.JTextField();
        lblUsuario = new javax.swing.JLabel();
        lblPassword = new javax.swing.JLabel();
        lblConfirmarPW = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        txtPasswordNuevo = new javax.swing.JPasswordField();
        txtConfirmarPassword = new javax.swing.JPasswordField();
        lblPerfil = new javax.swing.JLabel();
        txtIDPerfil = new javax.swing.JTextField();
        txtPerfil = new javax.swing.JTextField();
        btnBuscarPerfil = new javax.swing.JButton();
        botonSalir = new javax.swing.JButton();
        botonGuardar = new javax.swing.JButton();

        setResizable(true);
        setTitle("Nuevo Usuario");
        setMaximumSize(new java.awt.Dimension(550, 350));
        setMinimumSize(new java.awt.Dimension(550, 350));
        setPreferredSize(new java.awt.Dimension(550, 350));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos de Usuario"));

        lblEmpleado.setText("Empleado");

        btnBuscarEmpleado.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar2.png"))); // NOI18N
        btnBuscarEmpleado.setToolTipText("Buscar");
        btnBuscarEmpleado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarEmpleadoActionPerformed(evt);
            }
        });

        txtIDEmpleado.setEditable(false);
        txtIDEmpleado.setVisible(false);

        txtEmpleado.setEditable(false);

        lblUsuario.setText("Usuario");

        lblPassword.setText("Contraseña");

        lblConfirmarPW.setText("Confirmar Contraseña");

        lblPerfil.setText("Perfil");

        txtIDPerfil.setEditable(false);
        txtIDPerfil.setVisible(false);

        txtPerfil.setEditable(false);

        btnBuscarPerfil.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar2.png"))); // NOI18N
        btnBuscarPerfil.setToolTipText("Buscar");
        btnBuscarPerfil.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarPerfilActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblEmpleado)
                            .addComponent(lblPerfil, javax.swing.GroupLayout.Alignment.LEADING))
                        .addGap(25, 25, 25)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtIDEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtIDPerfil, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(lblUsuario)
                    .addComponent(lblPassword)
                    .addComponent(lblConfirmarPW))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(txtUsuario, javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(txtConfirmarPassword, javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(txtPasswordNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtPerfil, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnBuscarEmpleado)
                            .addComponent(btnBuscarPerfil))))
                .addGap(0, 29, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblEmpleado)
                    .addComponent(btnBuscarEmpleado)
                    .addComponent(txtIDEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPerfil)
                    .addComponent(txtIDPerfil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtPerfil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBuscarPerfil))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblUsuario)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPassword)
                    .addComponent(txtPasswordNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblConfirmarPW)
                    .addComponent(txtConfirmarPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 0, Short.MAX_VALUE))
        );

        botonSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        botonSalir.setToolTipText("Salir");
        botonSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonSalirActionPerformed(evt);
            }
        });

        botonGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/grabar.png"))); // NOI18N
        botonGuardar.setToolTipText("Guardar");
        botonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonGuardarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(botonGuardar)
                .addGap(1, 1, 1)
                .addComponent(botonSalir)
                .addGap(8, 8, 8))
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(59, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(botonGuardar, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(botonSalir, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap(52, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonGuardarActionPerformed
        ValidacionService validacionservice = new ValidacionService();
        Mensajes mensajes = new Mensajes();
        if ((validacionservice.esVacio(this.txtUsuario)) || (validacionservice.esVacio(this.txtPasswordNuevo)) || (validacionservice.esVacio(this.txtConfirmarPassword))) {
            JOptionPane.showInternalMessageDialog(this.getRootPane(), mensajes.getCompletarCampos(), "Aviso", JOptionPane.WARNING_MESSAGE);
        } else {
            UsuarioService usuarioService = new UsuarioService();
            String nuevoPassword = usuarioService.encrypt(String.valueOf(this.txtPasswordNuevo.getPassword()));
            String confirmaNuevoPassword = usuarioService.encrypt(String.valueOf(this.txtConfirmarPassword.getPassword()));
            String username = this.txtUsuario.getText();
            EmpleadoService empleadoService = new EmpleadoService();
            PerfilService perfilService = new PerfilService();
            if (!(nuevoPassword.equals(confirmaNuevoPassword))) {
                JOptionPane.showMessageDialog(this, "Los passwords no coinciden",
                        "Error Passwords",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                try {
                    //verificaré si el usuario ya está en uso 
                    //Obtiene el objecto Empleado con el ID ingresado
                    ObjectContext context = DataContext.createDataContext();
                    //si no se cae ...funciona ? =S 
                    List<Usuario> listaUsuario = usuarioService.buscarUsuario(username);
                    if (listaUsuario.isEmpty()) { //no encontré ningún usuario con ese fuking nombre
                      
                        //verificar el password
                        String mensaje = validacionservice.validaPassword(String.valueOf(this.txtConfirmarPassword.getPassword()));
                        if(mensaje!=null){
                            JOptionPane.showConfirmDialog(this,mensaje,"Aviso!",JOptionPane.CLOSED_OPTION,JOptionPane.INFORMATION_MESSAGE);
                        }
                        else {
                               Empleado emp = empleadoService.buscarEmpleadoporID(Integer.parseInt(this.txtIDEmpleado.getText()));

                        //Obtiene el objecto Perfil con el ID ingresado     
                        Perfil perf = perfilService.buscarPerfilporID(Integer.parseInt(this.txtIDPerfil.getText()));
                        //creo el usuario de miercoles
                        usuarioService.crear_usuario(username, emp.getIdempleado(), perf.getIdperfil(), nuevoPassword);
                        
                        
                        JOptionPane.showMessageDialog(this, mensajes.getRegistrado(),
                                "Creacion de usuario",
                                JOptionPane.INFORMATION_MESSAGE);
                        this.dispose();
                        }
                     
                    } else {
                        JOptionPane.showMessageDialog(this, "Ya existe un usuario con el nombre de " + username + "",
                                "Error de creación de usuarios",
                                JOptionPane.ERROR_MESSAGE);
                    }

                } catch (Exception e) {

                    JOptionPane.showMessageDialog(this, mensajes.getError(), "Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            }

        }



    }//GEN-LAST:event_botonGuardarActionPerformed

    private void botonSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonSalirActionPerformed
        ModulosT_SEG_AUsu admPermiso = new ModulosT_SEG_AUsu();
        this.getParent().add(admPermiso);

        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = admPermiso.getSize();
        admPermiso.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                (desktopSize.height - jInternalFrameSize.height) / 4);

        admPermiso.show();
        this.dispose();
    }//GEN-LAST:event_botonSalirActionPerformed

    private void btnBuscarEmpleadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarEmpleadoActionPerformed
        BusquedaEmpleado dialog = new BusquedaEmpleado(javax.swing.JOptionPane.getFrameForComponent(ModulosT_SEG_AUsuNuevo.this), true);
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
    }//GEN-LAST:event_btnBuscarEmpleadoActionPerformed

    private void btnBuscarPerfilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarPerfilActionPerformed
        BusquedaPerfil dialog = new BusquedaPerfil(javax.swing.JOptionPane.getFrameForComponent(ModulosT_SEG_AUsuNuevo.this), true);
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
    }//GEN-LAST:event_btnBuscarPerfilActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonGuardar;
    private javax.swing.JButton botonSalir;
    private javax.swing.JButton btnBuscarEmpleado;
    private javax.swing.JButton btnBuscarPerfil;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblConfirmarPW;
    private javax.swing.JLabel lblEmpleado;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblPerfil;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JPasswordField txtConfirmarPassword;
    public static javax.swing.JTextField txtEmpleado;
    public static javax.swing.JTextField txtIDEmpleado;
    public static javax.swing.JTextField txtIDPerfil;
    private javax.swing.JPasswordField txtPasswordNuevo;
    public static javax.swing.JTextField txtPerfil;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
